package com.blue.common;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.cxl.price.bean.Good;
import com.cxl.price.bean.Goods;
import com.cxl.price.bean.Imgs;
import com.cxl.price.bean.Shop;
import com.cxl.price.service.GoodService;
import com.cxl.price.service.GoodsService;
import com.cxl.price.service.ShopService;
import com.cxl.price.top.service.TopItemResponseService;
import com.taobao.api.ApiException;
import com.taobao.api.domain.Item;
import com.taobao.api.domain.ItemImg;

public class QuartzPrice  extends TransactionalQuartzTask  {
	
	
	private GoodsService goodsService;
	private GoodService goodService;
	private ShopService shopservice;
	private TopItemResponseService topItemResponseService;
	
	@Resource
	public void setTopItemResponseService(
			TopItemResponseService topItemResponseService) {
		this.topItemResponseService = topItemResponseService;
	}

	@Resource
	public void setShopservice(ShopService shopservice) {
		this.shopservice = shopservice;
	}
	
	@Resource
	 public void setGoodsService(GoodsService goodsService) {
		this.goodsService = goodsService;
	}

	@Resource
	 public void setGoodService(GoodService goodService) {
		this.goodService = goodService;
	}


	/**
	 * 匹配未有匹配的
	 */
	public void searchUrl()
     {
		Date start=new Date();
		List<Shop> shopList=shopservice.getAll();
		List<Goods> goodsList=goodsService.getListByHql("select g from Goods g");
		
		int i=0;
		for(Goods goods:goodsList)
		{
			List<Good> goodList=goodService.getListByHql("from Good g where g.goods.id='"+goods.getId()+"'");
			Set<Good> set = new HashSet<Good>(goodList);
			goods.setGood(set);
			i++;
			
			if(goods.isMatchGood()==false)
			{
				System.out.println("-------------------"+i+"正在匹配"+goods.getName()+"商品------------");
				try {
					goodsService.addSearchAllShopAndImport(shopList, goods);
				} catch (Exception e) {
					System.out.println("匹配"+goods.getName()+"商品时发生异常:"+e.getMessage());
				}
				
				

			}
		}
//		
//		//匹配价格最低的商店，或者匹配指定商店
		for(Goods goods:goodsList)
		{
			List<Good> goodList=goodService.getListByHql("from Good g where g.goods.id='"+goods.getId()+"'");
			Set<Good> set = new HashSet<Good>(goodList);
			goods.setGood(set);
		//	goodsService.clear();//清除session缓存
			goods.setNew_price(goodService.getMinPrice(goods));
			if(goods.isMatchGood()==false)
			{
			//未有锁定才去匹配
				goodsService.update(goods);
			}
		}
		timeToTime(start);
     }
	
public static boolean flag=true;
	

	/**
	 * 更新已经匹配的价格
	 * @throws ApiException 
	 */
	public void updatePrice() throws ApiException
	{
		
		updateGoodsInfo();
		if(flag==true)
		{
		flag=false;
		List<Good> goodList=goodService.getListByHql("select g from Good g left join fetch g.goods where g.goods.matchGood=true");
		for(Good good:goodList)
		{
				try {
				goodService.updatePrice(good);
				} catch (Exception e) {
					System.out.println("在"+good.getShop().getCnName()+"匹配"+good.getGoods().getName()+"商品时发生异常:"+e.getMessage());
				}
		}
		flag=true;
		}
		
		
	}
	
	
	/**
	 * 更新商品为最新信息
	 * @throws ApiException 
	 */
	public void updateGoodsInfo() throws ApiException
	{
		List<Goods> goodsList=goodsService.getListByHql("select g from Goods g");
		for(Goods goods:goodsList)
		{
			
			Long num_iid=goods.getNum_iid();
			
				Item item=topItemResponseService.getItemGetResponse(num_iid).getItem();
				goods.setName(item.getTitle());
				System.out.println(item.getSellerCids());
				goods.setPrice(Double.parseDouble(item.getPrice()));
				goods.setNum(item.getNum());
				goods.setTb_img(item.getPicUrl());
				goods.setDescription(item.getDesc());
				goods.setTb_url(item.getDetailUrl());
				goods.setOnSale(item.getApproveStatus());
				goods.setProduct_id(item.getProductId());
			//	goods.setVolume(item.getVolume());
				goods.setSynch(true);
				
				
				String propsName[]=item.getPropsName().split(";");
				String total="";
				for(String pr:propsName)
				{
					String cc[]=pr.split(":");
					if(cc.length==4)
					{
						total+=cc[2]+":"+cc[3]+";";
					}
					
				}
				goods.setPropsName(total);
				
				List<ItemImg> imgs=item.getItemImgs();
				//myImg.set
				Set<Imgs> set=goods.getImgsSet();
				Iterator<Imgs> iter=set.iterator();
				for(ItemImg img:imgs)
				{
					boolean has=false;
					Imgs myImg=new Imgs();
					myImg.setImg_url(img.getUrl());
					myImg.setImg_id(img.getId());
					myImg.setGoods(goods);
					while(iter.hasNext())
					{
						if(iter.next().getImg_url().equals(img.getUrl()))
						{
							has=true;
						}
					
					}
					if(!has)
					{
						goods.addImgs(myImg);
					}
				}
				goodsService.update(goods);
			}
		
		
		
	}

	@Override
	protected void executeTransactional(JobExecutionContext ctx)
			throws JobExecutionException {
		List<Shop> shopList=shopservice.getAll();
		List<Goods> goodsList=goodsService.getAll();
		
		for(Goods goods:goodsList)
		{
			if(goods.getGood().size()==0||goods.isMatchGood()==false)
			{
				try {
					goodsService.addSearchAllShopAndImport(shopList, goods);
				} catch (Exception e) {
					System.out.println("匹配"+goods.getName()+"商品时发生异常:"+e.getMessage());
				}
			}
		}
		
		
		System.out.println(goodsService);
           System.out.println("Quartz的任务调度！！！");
		
	}
	
	
	public   void timeToTime(Date date1)
	{
		Date date2=new Date();
		//SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		   long l=new Date().getTime()-date1.getTime();
		   long day=l/(24*60*60*1000);
		   long hour=(l/(60*60*1000)-day*24);
		   long min=((l/(60*1000))-day*24*60-hour*60);
		   long s=(l/1000-day*24*60*60-hour*60*60-min*60);
		   System.out.println(""+day+"天"+hour+"小时"+min+"分"+s+"秒");
	}
	
	public static void main(String[] args) {
		
		
	
	}


}
